package com.tenghui.assisting.service.impl;

import java.util.List;

import com.tenghui.assisting.vo.ShelfOperationVo;
import com.tenghui.common.enums.ListingStatus;
import com.tenghui.common.utils.DateUtils;
import com.tenghui.common.utils.SecurityUtils;
import com.tenghui.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tenghui.assisting.mapper.ProductsMapper;
import com.tenghui.assisting.domain.Products;
import com.tenghui.assisting.service.IProductsService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import static com.tenghui.common.core.domain.AjaxResult.error;
import static com.tenghui.common.utils.SecurityUtils.getUserId;

/**
 * 土特产产品Service业务层处理
 *
 * @author tenghui
 * @date 2025-10-27
 */
@Service
public class ProductsServiceImpl implements IProductsService
{
    @Autowired
    private ProductsMapper  productsMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 查询土特产产品
     *
     * @param productsId 土特产产品主键
     * @return 土特产产品
     */
    @Override
    public Products selectProductsByProductsId(String productsId)
    {
        return productsMapper.selectProductsByProductsId(productsId);
    }

    /**
     * 查询土特产产品列表
     *
     * @param products 土特产产品
     * @return 土特产产品
     */
    @Override
    public List<Products> selectProductsList(Products products)
    {
        // 当前登录用户的ID
        Long loginUserId = getUserId();
        // 将当前ID作为过滤条件，实现数据隔离
        if (!SecurityUtils.isAdmin(loginUserId)) {
            // 如果当前用户不是管理员 只显示自己创建的产品
            products.setUserId(loginUserId);
        }
        // 如果是管理员 显示所有用户的产品
        return productsMapper.selectProductsList(products);
    }

    /**
     * 新增土特产产品
     *
     * @param products 土特产产品
     * @return 结果
     */
    @Override
    public int insertProducts(Products products)
    {
        products.setCreateTime(DateUtils.getNowDate());
        products.setProductsId(IdUtils.fastSimpleUUID());
        products.setUserId(getUserId());
        // 新增：设置默认状态为上架 字典值为1
        if(products.getListingStatus() == null) {
            products.setListingStatus(ListingStatus.ON_SHELF.getCode()); // 1-上架
        }
        return productsMapper.insertProducts(products);
    }

    /**
     * 批量新增土特产产品
     *
     * @param productss 土特产产品List
     * @return 结果
     */
    @Override
    public int batchInsertProducts(List<Products> productss)
    {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        int count = 0;
        if (!CollectionUtils.isEmpty(productss)) {
            try {
                for (int i = 0; i < productss.size(); i++) {
                    for (Products products : productss) {
                        products.setProductsId(IdUtils.fastSimpleUUID());
                        products.setUserId(getUserId());
                    }
                    int row = productsMapper.insertProducts(productss.get(i));
                    // 防止内存溢出，每100次提交一次,并清除缓存
                    boolean bool = (i >0 && i%100 == 0) || i == productss.size() - 1;
                    if (bool){
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                    count = i + 1;
                }
            }catch (Exception e){
                e.printStackTrace();
                // 没有提交的数据可以回滚
                sqlSession.rollback();
            }finally {
                sqlSession.close();
                return count;
            }
        }
        return count;
    }

    /**
     * 修改土特产产品
     *
     * @param products 土特产产品
     * @return 结果
     */
    @Override
    public int updateProducts(Products products)
    {
        return productsMapper.updateProducts(products);
    }

    /**
     * 批量删除土特产产品
     *
     * @param productsIds 需要删除的土特产产品主键
     * @return 结果
     */
    @Override
    public int deleteProductsByProductsIds(String[] productsIds)
    {
        return productsMapper.deleteProductsByProductsIds(productsIds);
    }

    /**
     * 删除土特产产品信息
     *
     * @param productsId 土特产产品主键
     * @return 结果
     */
    @Override
    public int deleteProductsByProductsId(String productsId)
    {
        return productsMapper.deleteProductsByProductsId(productsId);
    }

    /**
     * 查询土特产产品列表（无权限）
     */
    @Override
    public List<Products> selectAllList(Products products) {
        return productsMapper.selectProductsList(products);
    }

    /**
     * 上下架商品
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int shelfOperation(ShelfOperationVo shelfOperationVo) {
        String productsId = shelfOperationVo.getProductsId();
        String statusDescription = shelfOperationVo.getStatusDescription();
        if (productsId == null) {
            throw new IllegalArgumentException("商品ID不存在");
        }
        Products newProducts = productsMapper.selectProductsByProductsId(productsId);
        if (newProducts == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        System.out.println(newProducts);
        try {
            ListingStatus byDescription = ListingStatus.getByDescription(statusDescription);
            System.out.println(byDescription);
            switch (byDescription) {
                case OFF_SHELF ,SOLD_OUT->{
                    newProducts.setListingStatus(ListingStatus.OFF_SHELF.getCode());
                    return productsMapper.updateProducts(newProducts);
                }
                case ON_SHELF->{
                    newProducts.setListingStatus(ListingStatus.ON_SHELF.getCode());
                    return productsMapper.updateProducts(newProducts);
                }
                default -> error("不支持的操作类型："+statusDescription);
            }
        }catch (IllegalArgumentException e){
            return 0;
        }

        return 0;
    }
}
